#!/usr/bin/perl -w

use strict;

use Cwd qw/ abs_path /;
use Env qw(PATH);;
use File::Basename qw(fileparse);
use FindBin;
use lib "$FindBin::Bin";
use DICOM::DICOM;
use DCMARCH::Util qw/ Run expandTar isTarchive Meta /;
use Getopt::Tabular;

my $Execute = 1;
my $Verbose = 0;
my $Batch   = 0;
my $Me      = fileparse($0);

$PATH .= ":$FindBin::Bin";

my $Usage = <<USAGE;

Usage: $Me <tarchive|tarball|dicomdir> <tarchive|tarball|dicomdir>

USAGE

my $Help = <<HELP;

$Me explicitly verifies that a tarchive (or regular tarball with DICOM
files) matches a directory of DICOM files (i.e., that the tarchive was
created from the DICOM dir or tarball).

HELP

&Getopt::Tabular::SetHelp($Help, $Usage);

my @ArgTable = (
    ["General options", "section"],
    ["-verbose|-quiet", "boolean", 1, \$Verbose, "Be verbose"],
    ["-execute", "boolean", 1, \$Execute, "Execute commands"],
    ["-batch", "boolean", 1, \$Batch, "Do not report anything, only produce an exit value"],
   );

my @Args;
&GetOptions(\@ArgTable, \@ARGV, \@Args) || exit 1;

die $Usage if (@Args != 2);

$DCMARCH::Util::Debug   = $Verbose;
$DCMARCH::Util::Verbose = $Verbose;
$DCMARCH::Util::Execute = $Execute;


my $Exit = 1;

if (&isTarchive(@Args)) {
    my $meta1 = &Meta($Args[0]);
    die "Unable to extract meta file from $Args[0]\n" if (! $meta1);

    my $meta2 = &Meta($Args[1]);
    die "Unable to extract meta file from $Args[1]\n" if (! $meta2);

    $Exit = ($meta1 ne $meta2);
}
else {
    # Copy the args, extracting tar archives as needed. The result should
    # be a two-element array with dicom dirs to compare
    my @Xargs = map { ( -d ) ? $_ : (&expandTar(abs_path($_)))[1] } @Args;

    my @dicomSummaryCmd = ('dicomSummary.pl', $Xargs[0], '-compare', $Xargs[1]);
    
    push(@dicomSummaryCmd, '-verbose') if $Verbose;
    
    $Exit = &Run(@dicomSummaryCmd);
}

if (! $Batch) {
    if ($Exit) {
	warn "$Args[0] and $Args[1] do not match\n";
    }
    else {
	warn "$Args[0] and $Args[1] are identical\n";
    }
}

exit $Exit;
